#include "CVersionUpdater.h"
#include "CResourcePacker.h"


CVersionUpdater::CVersionUpdater() : VersionInfo(NULL) {}
CVersionUpdater::~CVersionUpdater()
{
	if (this->VersionInfo)
	{
		delete this->VersionInfo;
		this->VersionInfo = NULL;
	}
}

bool CVersionUpdater::Open(const ATL::CString& exeOrDll)
{
	DWORD handle = 0;
	DWORD blockBytesCount = GetFileVersionInfoSize(exeOrDll, &handle);
	if (blockBytesCount == 0) return false;

	BYTE* blockBytes = new BYTE[blockBytesCount];
	if (!GetFileVersionInfo(exeOrDll, NULL, blockBytesCount, blockBytes))
	{
		delete[]blockBytes;
		return false;
	}

	CVersionInfo* versionInfo = new CVersionInfo;
	versionInfo->Parse(blockBytes);
	delete[]blockBytes;

	if (this->VersionInfo) delete this->VersionInfo;
	this->VersionInfo = versionInfo;
	this->ExeOrDll = exeOrDll;

	return true;
}

bool CVersionUpdater::Update(WORD language_) const
{
	if (!this->VersionInfo) return false;

	HANDLE resource = BeginUpdateResource(this->ExeOrDll, FALSE);
	if (!resource) return false;

	CResourcePacker packer;
	this->VersionInfo->Pack(packer);

	if (!UpdateResource(resource, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), language_, packer.GetResource(), packer.GetSize())) return false;
	return EndUpdateResource(resource, FALSE);
}
